package com.infore.authorityManagement.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.infore.authorityManagement.entity.SysPermission;
import com.infore.authorityManagement.entity.SysRole;
import com.infore.authorityManagement.entity.SysRolePermission;
import com.infore.authorityManagement.entity.SysRoleStation;
import com.infore.authorityManagement.repository.ISysPermissionRepository;
import com.infore.authorityManagement.repository.ISysRolePermissionRepository;
import com.infore.authorityManagement.repository.ISysRoleRepository;
import com.infore.authorityManagement.repository.ISysRoleStationRepository;
import com.infore.authorityManagement.service.ISysPermissionService;
import com.infore.authorityManagement.service.ISysRoleService;
import com.infore.authorityManagement.util.Page;
import com.infore.authorityManagement.util.PageUtil;
import com.infore.authorityManagement.util.UUIDGenerator;


@Service
@Transactional
public class SysRoleServiceImpl implements ISysRoleService {
    
    @Autowired
    ISysRoleRepository sysRoleRepository;
    @Autowired
    ISysRoleStationRepository roleStationRepository;
    @Autowired
    ISysRolePermissionRepository sysRolePermissionRepository;
    @Autowired
    ISysPermissionService sysPermissionService;
    
    @Override
    public SysRole getRoleById(String roleId) {
        SysRole role = sysRoleRepository.findById(roleId).orElse(null);
        return role;
    }

    @Override
    public List<SysRole> getRoles(SysRole sysRole) {
        List<SysRole> list = new ArrayList<SysRole>();
        if (sysRole.getRoleName() != null && !"".equals(sysRole.getRoleName())) {
            list = sysRoleRepository.findByRoleNameLike(sysRole.getRoleName());
        }else {
            list = sysRoleRepository.findAll(); 
        }
        return list;
    }

    @Override
    public Page<SysRole> getRolesForPage(SysRole sysRole, Integer pageSize, Integer pageNo) {
        Pageable pageable = PageRequest.of(pageNo-1, pageSize);
        Page<SysRole> rolePage = null;
        if (!StringUtils.isBlank(sysRole.getRoleName())) {
            org.springframework.data.domain.Page<SysRole> page = sysRoleRepository.findByRoleNameLike(sysRole.getRoleName(), pageable);
            rolePage = PageUtil.pageConvert(page);
        }else {
            org.springframework.data.domain.Page<SysRole> page = sysRoleRepository.findAll(pageable);
            rolePage = PageUtil.pageConvert(page); 
        }
        return rolePage;
    }

    @Override
    public Page<SysRole> getRolesWidthParent(SysRole sysRole, Integer pageSize, Integer pageNo) {
        return null;
    }

    @Override
    public Map<String, Object> addRole(SysRole sysRole) {
        Map<String, Object> map = new HashMap<String, Object>();
        int resultIdt = 0;
        SysRole r = getRoleByName(sysRole.getRoleName());
        if (r != null) {
            resultIdt = -1;        //该角色名称已经存在
            map.put("resultIdt", resultIdt);
            return map;
        }
        java.util.Date date = new java.util.Date();
        long d = date.getTime();
        Timestamp timestamp = new Timestamp(d);
        sysRole.setCreateTime(timestamp);
        try {
            sysRole = sysRoleRepository.saveAndFlush(sysRole);
        } catch (Exception ex) {
            resultIdt = -2;
            map.put("resultIdt", resultIdt);
            return map;
        }
        map.put("resultIdt", resultIdt);
        map.put("roleId", sysRole.getRoleId());
        return map;
    }

    private SysRole getRoleByName(String roleName) {
        return sysRoleRepository.findByRoleName(roleName);
    }

    @Override
    public int updateRoles(SysRole sysRole) {
        SysRole r = getRoleById(sysRole.getRoleId());
        int resultIdt = 0;
        if (r == null) {
            return -1;        //该角色不存在
        }
        
        if (checkRoleNameExist(sysRole.getRoleId(), sysRole.getRoleName())) {
            return -2;        //该角色名称已经存在
        }
        if (!StringUtils.isBlank(sysRole.getRoleName())) {
            r.setRoleName(sysRole.getRoleName());
        }
        if (!StringUtils.isBlank(sysRole.getDescription())) {
            r.setDescription(sysRole.getDescription());
        }
        if (sysRole.getSeqNum() != null) {
            r.setSeqNum(sysRole.getSeqNum());
        }
        if (sysRole.getCreateTime() != null) {
            r.setCreateTime(sysRole.getCreateTime());
        }
        try {
            sysRoleRepository.saveAndFlush(r);
        } catch (Exception ex) {
            resultIdt = -3;
        }
        return resultIdt;
    }

    private boolean checkRoleNameExist(String roleId, String roleName) {
        SysRole sysRole = sysRoleRepository.findByRoleIdNotAndRoleName(roleId, roleName);
        if(sysRole != null) {
            return true;
        }
        return false;
    }

    @Override
    public int deleteRoleById(String roleId) {
        try {
            sysRoleRepository.deleteById(roleId);
        } catch (Exception ex) {
            return -2;
        }
        return 0;
    }

    @Override
    public int addRoleStations(String roleId, String[] stationIds) {
        SysRole sysRole = getRoleById(roleId);
        if (sysRole == null) {
            return -1;    //角色不存在
        }
        roleStationRepository.deleteAll(getRoleStations(roleId));
        List<SysRoleStation> list = new ArrayList<>();
        SysRoleStation sysRoleStation = null;
        for (String stationId : stationIds) {
            sysRoleStation = new SysRoleStation();
            sysRoleStation.setId(UUIDGenerator.getUUID());
            sysRoleStation.setRoleId(roleId);
            sysRoleStation.setStationId(stationId);
            list.add(sysRoleStation);
        }
        roleStationRepository.saveAll(list);
        return 0;
    
    }

    
    @Override
    public List<SysRoleStation> getRoleStations(String roleId) {
        return roleStationRepository.findByRoleId(roleId);
    }

    @Override
    public int addRolePermissions(String roleId, String[] permissionArray) {

        SysRole sysRole = getRoleById(roleId);
        if (sysRole == null) {
            return -1;    //角色不存在
        }
        sysRolePermissionRepository.deleteAll(sysRolePermissionRepository.findByRoleId(roleId));
        List<SysRolePermission> list = new ArrayList<>();
        for (String permissionId : permissionArray) {
            SysRolePermission sysRolePermission = new SysRolePermission();
            list.add(sysRolePermission);
            sysRolePermission.setId(UUIDGenerator.getUUID());
            sysRolePermission.setRoleId(roleId);
            sysRolePermission.setPermissionId(permissionId);
        }
        sysRolePermissionRepository.saveAll(list);
        return 0;
    
    }

    @Override
    public List<SysPermission> getRolePermissionMenu(String roleId, String appCode) {
        List<SysPermission> result = new ArrayList<>();
        SysPermission permission = null;
        List<SysRolePermission> list = sysRolePermissionRepository.findByRoleId(roleId);
        for (SysRolePermission sysRolePermission : list) {
            String permissionId = sysRolePermission.getPermissionId();
            permission = sysPermissionService.getPermissionById(permissionId);
            if(permission != null) {
                if(StringUtils.isBlank(appCode) || permission.getAppCode().equals(appCode)) {
                    result.add(sysPermissionService.getPermissionById(permissionId));
                }
            }
        }
        return result;
    }
    
    @Override
    public List<SysRolePermission> getRolePermissions(String roleId) {
        return sysRolePermissionRepository.findByRoleId(roleId);
    }

}
